﻿using System.Text;

namespace LeetCodeProject._0001_1000._001_100._006;

public class Solution
{
    /// <summary>
    /// 方法一：利用二维矩阵模拟
    /// </summary>
    /// <param name="s"></param>
    /// <param name="numRows"></param>
    /// <returns></returns>
    public string Convert(string s, int numRows)
    {
        int n = s.Length, r = numRows;
        if (r == 1 || r >= n)
        {
            return s;
        }

        int t = r * 2 - 2;
        int c = (n + t - 1) / t * (r - 1);
        char[][] mat = new char[r][];
        for (int i = 0; i < r; ++i)
        {
            mat[i] = new char[c];
        }

        for (int i = 0, x = 0, y = 0; i < n; ++i)
        {
            mat[x][y] = s[i];
            if (i % t < r - 1)
            {
                ++x; // 向下移动
            }
            else
            {
                --x;
                ++y; // 向右上移动
            }
        }

        StringBuilder ans = new StringBuilder();
        foreach (char[] row in mat)
        {
            foreach (char ch in row)
            {
                if (ch != 0)
                {
                    ans.Append(ch);
                }
            }
        }

        return ans.ToString();
    }


    /// <summary>
    /// 方法二：压缩矩阵空间
    /// </summary>
    /// <param name="s"></param>
    /// <param name="numRows"></param>
    /// <returns></returns>
    public string Convert2(string s, int numRows)
    {
        int n = s.Length, r = numRows;
        if (r == 1 || r >= n)
        {
            return s;
        }

        StringBuilder[] mat = new StringBuilder[r];
        for (int i = 0; i < r; ++i)
        {
            mat[i] = new StringBuilder();
        }

        for (int i = 0, x = 0, t = r * 2 - 2; i < n; ++i)
        {
            mat[x].Append(s[i]);
            if (i % t < r - 1)
            {
                ++x;
            }
            else
            {
                --x;
            }
        }

        StringBuilder ans = new StringBuilder();
        foreach (StringBuilder row in mat)
        {
            ans.Append(row);
        }

        return ans.ToString();
    }
}